今天做昨天說到file owner的詳細實作方法
注意:這邊的Class是說file owner的類型,而非與MainView產生連結要產生連結要在MainView.swift檔案中,添加程式碼去綁定
那麼MainView.swift裡面應該要有些什麼

讓MainView.swift知道我們xib裡面有些什麼元件他要負責顯示
什麼是NibLoadable?
是一個方便使用的框架,可以負責用來載入Nib檔案
該如何使用NibLoadable?
創立一個NibLoadble.swift檔案,輸入以下
protocol NibOwnerLoadable: AnyObject {
    static var nib: UINib { get }
}
// MARK: - Default implmentation
extension NibOwnerLoadable {
    
    static var nib: UINib {
        UINib(nibName: String(describing: self), bundle: Bundle(for: self))
    }
}
// MARK: - Supporting methods
extension NibOwnerLoadable where Self: UIView {
    
    func loadNibContent() {
        guard let views = Self.nib.instantiate(withOwner: self, options: nil) as? [UIView],
            let contentView = views.first else {
                fatalError("Fail to load \(self) nib content")
        }
        self.addSubview(contentView)
        contentView.translatesAutoresizingMaskIntoConstraints = false
        contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        contentView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        contentView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
    }
}
這部分是參考Jeremy Xue大神,參考連結附在下面
MainView.swift透過繼承NibOwnerLoadable的這個Class

使用這個名字為loadNibContent的protocol 來綁定名字與自身相同的xib檔案

為了讓loadNibContent能夠使用,我們在初始化的狀態下調用loadNibContent


Swift- 創建自定義視圖
Understanding Custom UIView In-depth: Setting File Owner vs custom class